package com.android.djlmapp.model.my;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.NotificationBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.android.djlmapp.R;
import com.android.djlmapp.dialog.BaseDialog;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.tools.msg.ExampleUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * CheckVersionLib更新库自定义
 */
public class UpdateInfo {
    public static final String TAG = "djlm-my: ";
    public Context mContext;
    public static boolean showTost = false; //显示已是最新Tost
    public String version;
    public DownloadBuilder builder;

    public UpdateInfo(Context context){
        mContext = context;
    }

    public static boolean getIsUpdate() {
        return showTost;
    }

    public void update() {
        builder = AllenVersionChecker
                .getInstance()
                .requestVersion()
                .setRequestUrl(GlobalUrls.UPDATE_URL)
                .request(new RequestVersionListener() {
                    @Nullable
                    @Override
                    public UIData onRequestVersionSuccess(String result) {
                        Log.i(TAG , result);

                        try {
                            JSONObject o = new JSONObject(result);
                            version = o.optString("version");

                            //版本对比
                            if(conpileVersion(version)){

                                String title = o.optString("name");
                                Log.i(TAG, "title: " + title);

                                String path = o.optString("path");
                                Log.i(TAG, "path: " + path);

                                JSONArray listArr = o.optJSONArray("list");

                                StringBuilder strContent = new StringBuilder();
                                for (int i = 0; i < listArr.length(); i++) {
                                    strContent.append(listArr.optString(i) + "\r\n");
                                }
                                Log.i(TAG, "title: " + strContent);

                                return crateUIData(title, path, strContent.toString());
                            }else{
                                showTost = true;
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        return null;
                    }

                    @Override
                    public void onRequestVersionFailure(String message) {
                        Log.i(TAG , message);
                    }
                });

//            //强制更新
//            forceUpdate();

        //静默下载
        builder.setSilentDownload(false); //默认false

        //设置当前服务器最新的版本号，供库判断是否使用缓存
        if(version != null && !version.isEmpty()) {
            builder.setNewestVersionCode(Integer.parseInt(version.replace(".", ""))); //默认null
        }

        //如果本地有安装包缓存也会重新下载apk
        builder.setForceRedownload(false); //默认false

        //是否显示下载对话框
        builder.setShowDownloadingDialog(true); //默认true

        //是否显示失败对话框
        builder.setShowDownloadFailDialog(true);//默认true

//        builder.setOnCancelListener(() -> {
////            Toast.makeText(mContext, "Cancel Hanlde", Toast.LENGTH_SHORT).show();
//        });

        //更新界面选择
        builder.setCustomVersionDialogListener(createCustomDialogTwo());

        //是否显示通知栏
        builder.setShowNotification(true);  //默认true
        //自定义通知栏
        builder.setNotificationBuilder(
                NotificationBuilder.create()
                        .setRingtone(true)
                        .setIcon(R.mipmap.logo_icon)

        );

        builder.executeMission(mContext);
    }


    /**
     * @return
     * @important 使用请求版本功能，可以在这里设置downloadUrl
     * 这里可以构造UI需要显示的数据
     * UIData 内部是一个Bundle
     */
    private UIData crateUIData(String title, String path, String content) {
        UIData uiData = UIData.create();
        uiData.setTitle(title);
        uiData.setDownloadUrl(path);
        uiData.setContent(content);
        return uiData;
    }

    public static CustomVersionDialogListener createCustomDialogTwo() {
        return (context, versionBundle) -> {
            BaseDialog baseDialog = new BaseDialog(context, R.style.BaseDialog, R.layout.custom_dialog_two_layout);
            TextView textTitle= baseDialog.findViewById(R.id.tv_title);
            textTitle.setText(versionBundle.getTitle());
            TextView textView = baseDialog.findViewById(R.id.tv_msg);
            textView.setText(versionBundle.getContent());
            baseDialog.setCanceledOnTouchOutside(true);
            return baseDialog;
        };
    }

//    /**
//     * 强制更新操作
//     * 通常关闭整个activity所有界面，这里方便测试直接关闭当前activity
//     */
//    private void forceUpdate() {
//        Toast.makeText(mContext, "force update handle", Toast.LENGTH_SHORT).show();
//        finish();
//    }

    /**
     * 版本对比
     * @param version
     * @return
     */
    public boolean conpileVersion(String version){
        try {
            //本地版本
            String versionLoc = ExampleUtil.GetVersion(mContext);
            Log.i(TAG, "versionLoc: " +versionLoc);

            //线上版本
            Log.i(TAG, "version: " +version);

            //版本对比
            if(!versionLoc.isEmpty() && !version.isEmpty()) {
                //截取位数一致
                Long version_online =  versionInt(version);
                Long version_Loc =  versionInt(versionLoc);

                Log.i(TAG, "version.length(): " +version.length());
                Log.i(TAG, "versionLoc.length(): " +versionLoc.length());

                if(version.length() != versionLoc.length()){
                    if(version.length() < versionLoc.length()){
                        version_Loc =  versionInt(
                                ("" +version_Loc).substring(0, ("" +version_online).length())
                        );
                    }else{
                        version_online =  versionInt(
                                ("" +version_online).substring(0, ("" +version_Loc).length())
                        );
                    }
                    Log.i(TAG, "version_Loc: " +version_Loc);
                    Log.i(TAG, "version_online: " +version_online);
                }

                if (version_online > version_Loc) {
                    return true;
                }
            }
        }catch (Exception e){}

        return false;
    }

    /**
     * 版本int
     * @param version
     * @return
     */
    public static Long versionInt(String version){
        return Long.parseLong(version.replace(".", ""));
    }

}
